﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using blackhouse.BlackApart.Business.Opinions;
using blackhouse.BlackApart.Web;
using blackhouse.BlackApart.Web.Navigation;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web;

namespace blackhouse.Aparts.Web.Navigation {
    public class CmsUrlOpinionVisitor : UrlVisitor, IOpinionVisitor {

        #region Fields

        private CmsUrlHelper helper;
        private string savedUrl;
        private string suggestedUrl;
        private IOpinion opinion;

        #endregion

        public void Apply(IOpinion opinion) {
            this.helper = new CmsUrlHelper("Opinion");
            this.opinion = opinion;
            this.savedUrl = helper.GetUrl(opinion.Id);
            this.suggestedUrl = this.SuggestUrl(opinion);
            this.EnsureCmsUrlExists();
            this.Url = this.savedUrl;
        }

        private string SuggestUrl(IOpinion opinion) {
            string url = opinion.Publisher.FirstName;
            if (!string.IsNullOrEmpty(opinion.Publisher.LastName))
                url = url + "-" + opinion.Publisher.LastName;
            url += "-";
            url += opinion.PublishedDate.ToString("D");
            url += "-";
            url += opinion.GetAssociatedApartmentGroup().ShortName.CleanStringForUrl();
            url = url.CleanStringForUrl().RemovePolishChars().ToLower();
            return url;
        }

        private void EnsureCmsUrlExists() {
            if (string.IsNullOrEmpty(this.savedUrl)) {
                this.helper.SaveUrl(this.opinion.Id, this.suggestedUrl);
                this.helper.AddCmsUrl(this.suggestedUrl, "/pages/opiniondetails.aspx?opinion=" + this.opinion.Id);
                this.savedUrl = this.suggestedUrl;
            }
        }

    }
}